package com.zq.config;

import com.zq.shiro.CustomRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import java.util.LinkedHashMap;
import java.util.Properties;

/**
 * 把subject 和securityManager realm 关联
 *
 * @author Administrator
 */


@Configuration
public class ShrioConfig {
	
	/**
	 * 使用注解设置权限
	 */
	@Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

	/**
	 * 配置shiro拦截器
	 * @return
	 */
	@Bean
	public  ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
		//shiro的过滤器对象，拦截请求进行验证
		ShiroFilterFactoryBean shiroFilterFactoryBean=new ShiroFilterFactoryBean();
	    shiroFilterFactoryBean.setSecurityManager(securityManager);
//	    Map<String, Filter> filterMapCros = new LinkedHashMap<String, Filter>();
//	    filterMapCros.put("/*",""); 
//	    shiroFilterFactoryBean.setFilters(filterMapCros);
	    //配置访问权限链 linked保证有序
	    LinkedHashMap<String, String> filterMap=new LinkedHashMap<String, String>();
	    
	    /**
	     * 第一个参数：访问路径，第二个：权限
	     * anon：没有限制
	     * authc：必须登录后才能访问
	     * user：remember me使用	
	     * prems：必须有相应的权限才能操作
	     * roles：必须有角色的权限才能操作 
	     */
	    
	     filterMap.put("/login", "anon");
	     shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);

	     return  shiroFilterFactoryBean;
	}
	/**
	 * 配置shiro核心管理器
	 * 
	 * @return
	 */
	@Bean
	public SecurityManager securityManager() {
		//shiro的核心管理
		DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
		//把realm注入到manager中
		securityManager.setRealm(customRealm());
		
		return securityManager;
	}

	/**
	 * 配置自定义realm
	 * @return
	 */
	@Bean
	public CustomRealm customRealm() {
		
		return new CustomRealm();
	}
	
}
